<!-- 登录页面 -->
<template>
    <div id='login_container'>
        <div id="title">在线聊天室</div>
        <!-- 登录表单 -->
        <el-form :model="form" label-width="auto" style="max-width: 300px; margin-top: 15px;" id="form_ipt">
            <el-form-item label="邮箱：">
                <el-input v-model="form.email" placeholder="输入邮箱" />
            </el-form-item>
            <el-form-item label="密码：">
                <el-input v-model="form.password" placeholder="请输入密码" type="password" @keyup.enter="loginHandler"/>
            </el-form-item>
        </el-form>
        <div id="register" @click="registerHandle">没有账号?</div>
        <div id="login_btn">
            <el-button type="primary" plain @click="loginHandler">登录</el-button>
        </div>
    </div>
</template>
<script setup>
import { saveValue, getValueBykey } from '../src/indexDB/dbKV.js'; // 存储登录后的token和用户信息
import { ref } from "vue";
import axios from "../public/axiosConfig.js"
import { ElMessage } from 'element-plus'

// 登录参数
let form = ref({
    email: "",
    password: ""
})

// 登录处理器
async function loginHandler() {
    // 判空
    if (form.value.email == "" || form.value.password == "") {
        ElMessage({
            message: '输入为空!',
            type: 'info',
        })
        return 0;
    }
    // 判断邮箱格式
    if (!isValidEmail(form.value.email)) {
        ElMessage({
            message: '邮箱格式不正确!',
            type: 'error',
        });
        return 0;
    }

    const res = await axios.post("/userInfos/login", form.value);
    // console.log("登录结果", res);
    if(res.data.code == 0){
        ElMessage({ 
            message: res.data.msg,
            type: 'error',
        });
        return 0;
    }
    // 解析返回字符串中的用户信息，转为对象存入indexDB中
    saveValue("userInfo",parseResponse(res.data.data))
    saveValue("token",res.headers.authorization)
    
    // 页面跳转
    window.location.href = "/";
}

// 判断邮箱格式的函数
function isValidEmail(email) {
    // 正则表达式，用于验证邮箱格式
    const emailRegex = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
    return emailRegex.test(email);
}

// 解析后端返回的字符串对象为 JavaScript 对象
function parseResponse(responseString) {
  // 移除对象前后的括号和多余的空格
  responseString = responseString.replace(/^\w+\(/, '').replace(/\)$/, '').trim();

  // 将字符串按逗号分隔成属性对
  const pairs = responseString.split(/,\s*/);

  // 将属性对转为对象
  const obj = {};
  pairs.forEach(pair => {
    const [key, value] = pair.split(/=(.+)/); // 只分隔第一次出现的 =
    obj[key.trim()] = value.trim();
  });

  return obj;
}

// 注册处理器
function registerHandle(){
    // 跳转到注册页面
    window.location.href = "/register/"
}


</script>
<style scoped>
#login_btn {
    display: flex;
    justify-content: center;
    padding-top: 4px;
}

#register{
    font-size: 14px;
    color: #5a5a5a;
    width: 90%;
    display: flex;
    justify-content: right;
    padding-right: 10px;
    position: relative;
    bottom: 8px;
}

#login_btn button {
    width: 100px;
    height: 40px;
}

#title {
    padding: 15px 0px;
    text-align: center;
    font-family: "幼圆";
    font-size: 18px;
}

#login_container {
    /* border: solid 1px red; */
    max-width: 800px;
    margin: 0 auto;
}

#form_ipt {
    /* border: solid 1px red; */
    margin: 0 auto;
}
</style>